// modules =================================================
var express        = require('express');
var app            = express();
var port           = process.env.PORT || 3000; // set our port
var morgan         = require('morgan');
var cookieParser   = require('cookie-parser');
var bodyParser     = require('body-parser');
var session        = require('express-session');
var methodOverride = require('method-override');
var request        = require('request');
var mongoskin	   = require('mongoskin');

var passport       = require('passport');
var flash          = require('connect-flash');
// configuration ===========================================

// setup mongodb connection
var config = require('./config/config');
var ObjectID = mongoskin.ObjectID;
var db = mongoskin.db(config.MONGO_DB_URL, {native_parser:true, poolSize: 3, auto_reconnect: true, numberOfRetries: 2, retryMiliSeconds: 3000});
/*var MongoClient = mongoskin.MongoClient;
var db = MongoClient.connect(config.MONGO_DB_URL, {native_parser:true, poolSize: 5, numberOfRetries: 2});*/

// setup express
app.use(express.static(__dirname + '/public')); 	// set the static files location /public/img will be /img for users
app.use(morgan('dev')); 					        // log every request to the console
app.use(cookieParser());                            // read cookies (needed for auth)
app.use(bodyParser.json()); 						// pull information from html in POST?, get information from html forms?
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride()); 					        // simulate DELETE and PUT

// setup template engine
//app.engine('handlebars', handlebars({defaultLayout: 'index'}));
app.set('view engine', 'ejs'); // set up ejs for serving template

// setup passport
app.use(session({ secret: 'welovecoding', saveUninitialized: true, resave: true })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

// Authentication & Authorization utilities functions
var authUtil = require('./app/authUtil');

// include passport module with local strategy ===========================================================
require('./app/passport')(passport, db, authUtil);

// template routes =======================================================================================
require('./app/templateRoute')(app, passport, authUtil);

// REST API =======================================================================================
require('./app/apiRoute')(app, db, config.DDA_SERVER_URL, request, authUtil, ObjectID);

app.use(function (err, req, res, next) {
    if (err){
        console.error(err);
        res.json({"status": "ERROR", "msg": "Oops, there was an error"});
    }
});

// start app ===============================================
app.listen(port);
console.log('Magic happens on port ' + port);
//exports = module.exports = app; 						// expose app